package com.aizuda.easyManagerTool.service.gpt.impl;

import cn.hutool.core.util.ObjectUtil;
import com.aizuda.easy.security.domain.Rep;
import com.aizuda.easy.security.domain.Req;
import com.aizuda.easyManagerTool.domain.entity.gpt.GPTSettingEntity;
import com.aizuda.easyManagerTool.domain.vo.setting.SettingUserVO;
import com.aizuda.easyManagerTool.mapper.gpt.GPTSettingMapper;
import com.aizuda.easyManagerTool.service.gpt.GPTModel;
import com.aizuda.easyManagerTool.service.gpt.GPTSettingService;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

@Service
public class GPTSettingServiceImpl implements GPTSettingService, CommandLineRunner {

    @Resource
    private GPTSettingMapper gptSettingMapper;

    @Override
    public Rep<GPTSettingEntity> find(Req<GPTSettingEntity, SettingUserVO> req) {
        GPTSettingEntity gptSettingEntity = gptSettingMapper.find();
        if(ObjectUtil.isEmpty(gptSettingEntity)){
            gptSettingEntity = new GPTSettingEntity();
        }
        return Rep.ok(gptSettingEntity);
    }

    @Override
    public Rep<GPTSettingEntity> edit(Req<GPTSettingEntity, SettingUserVO> req) {
        GPTSettingEntity data = req.getData();
        if (ObjectUtil.isEmpty(data.getGsOpenAiProxy())) {
            data.setGsOpenAiProxy(false);
        }
        if (ObjectUtil.isEmpty(data.getId())) {
            // 插入
            gptSettingMapper.insert(data);
        }else{
            gptSettingMapper.updateById(data);
        }
        GPTModel gptModel = new GPTModel();
        gptModel.setGptSettingEntity(data);
        GPTModelManager.put(req.getUser().getTenantId(),gptModel);
        return Rep.ok(data);
    }


    @Override
    public void run(String... args) throws Exception {
        List<GPTSettingEntity> all = gptSettingMapper.findAll();
        all.forEach(item -> {
            GPTModel gptModel = new GPTModel();
            gptModel.setGptSettingEntity(item);
            GPTModelManager.put(item.getTenantId(),gptModel);
        });
    }
}
